# encoding: utf-8
# Author    : limusen
# Datetime  : 2023/9/22 11:41
# File      : tt1.py
# explain   : 文件说明

from time import time
from common.log import logger
from common.read_yaml import get_yml_data, revise_yml_data
from business.smartsync.login import Login


def get_or_refresh_token():
    max_retries = 3  # Maximum number of retries
    retry_count = 0

    while retry_count < max_retries:
        try:
            token_info = get_yml_data('config', 'token', 'token')[0]['palayod']
            current_time = token_info['current_time']
            if time() - current_time < 7200:
                return token_info['Authorization']

            response = Login().login(get_yml_data('sync', 'login', 'login_params')[0]['palayod'])
            new_token = response.json()['data']['Authorization']
            revise_yml_data('config', 'token', 'token', 'palayod', new_token, 'Authorization')
            revise_yml_data('config', 'token', 'token', 'palayod', int(time()), 'current_time')
            return new_token

        except TypeError:
            logger.error("尝试获取或刷新token时发生异常。重试...")
            retry_count += 1

    logger.error("重试 {} 后无法获取token信息.".format(max_retries))
    return None  # Return None or handle the failure according to your requirements


if __name__ == '__main__':
    print(get_or_refresh_token())
